package google.apps.reporting.utils;

import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.docs.DocumentEntry;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.net.URL;

/**
 * Uploads the generated report to Google Docs using
 * Admin credentials
 */
public class ReportUploaderUtil {

  public ReportUploaderUtil() {
  }
  
  
  public static String UPLOAD_URL =
   "http://docs.google.com/feeds/documents/private/full";

/**
   *  Util method to upload spreadsheets to Google Docs.
   *  Uses GData DocList API
   * @param userName  admin username
   * @param password  admin password
   * @param filePath  path of the document to be uploaded
   * @return URL of the document
   */
  public static String uploadWorkbook(String userName, String password,
                                    String filePath) {
    
    String link ="";
    try {
      File documentFile = new File(filePath);
      DocumentEntry newDocument = new DocumentEntry();
      newDocument.setFile(documentFile);

      // Set the title for the new document. For this example we just use the
      // filename of the uploaded file.
      newDocument.setTitle(new PlainTextConstruct(documentFile.getName()));
      DocsService service = new DocsService("ReportingUI");
      try {
        service.setUserCredentials(userName, password);
      } catch (AuthenticationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
      URL documentListFeedUrl = new URL(UPLOAD_URL);
      newDocument.addFolder(new Person(), "Reports");

      DocumentListEntry uploaded =
        service.insert(documentListFeedUrl, newDocument);
      System.out.println(uploaded.getHtmlLink().getHref()); 
      
      link = uploaded.getHtmlLink().getHref();

    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ServiceException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return link;
  }
 
}
